package com.tjs.lucky.application.worker;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.tjs.lucky.common.ActivityState;
import com.tjs.lucky.common.Result;
import com.tjs.lucky.domain.activity.model.vo.ActivityVO;
import com.tjs.lucky.domain.activity.repository.IActivityRepository;
import com.tjs.lucky.domain.activity.service.stateflow.StateHandler;
import com.tjs.lucky.domain.award.repository.IAwardRepository;
import com.tjs.lucky.infrastructure.utils.EmailUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Scope("prototype")  // 多例: 每次使用时创建，如果是单例，设置activityVO时会有线程安全问题。
@Slf4j
public class InitActivityJob implements SimpleJob {

    private ActivityVO activityVO;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IAwardRepository awardRepository;

    @Resource
    private IActivityRepository activityRepository;

    @Resource
    private EmailUtil emailUtil;

    @Resource
    private StateHandler stateHandler;


    public void setActivityVO(ActivityVO activityVO) {
        this.activityVO = activityVO;
    }

    @SneakyThrows
    @Override
    public void execute(ShardingContext shardingContext) {
        String jobName = shardingContext.getJobName();
        Long activityId = activityVO.getActivityId();
        emailUtil.sendhtml("928301810@qq.com", "定时任务触发啦！", jobName);
        Integer state = activityVO.getState();
        if(state == null ||(!state.equals(4) && !state.equals(5))){
            emailUtil.sendhtml("928301810@qq.com","活动状态异常！", jobName);
        }
        Result state4Result = stateHandler.doing(activityId, ActivityState.PASS);
        log.info("扫描活动状态为活动中 结果：{} activityId：{} activityName：{} creator：{}", JSON.toJSONString(state4Result), activityId, activityVO.getActivityName(), activityVO.getCreator());
        try {
            //缓存奖品库存
            log.info(jobName +":缓存奖品库存,activityId:"+activityId);
            activityAwardAddToRedis(activityId);
            //缓存活动库存
            String actKey = "activityTotalCount:" + activityId;
            ActivityVO activityVO = activityRepository.queryActivityInfo(activityId);
            String activityTotalCount = String.valueOf(activityVO.getStockCount() == null ? -1 : activityVO.getStockCount());
            log.info(jobName +":缓存活动库存："+activityTotalCount);
            stringRedisTemplate.opsForValue().setIfAbsent(actKey, activityTotalCount);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            stringRedisTemplate.opsForHash().putIfAbsent("activeActivitys",String.valueOf(activityId),dateFormat.format(activityVO.getEndDateTime()));
        }catch (Exception e){
            emailUtil.sendhtml("928301810@qq.com", "定时任务出错啦！", jobName +"："+e.getMessage());
        }
    }


    public void activityAwardAddToRedis(Long activityId) {
        Map<String, String> idCountMap = awardRepository.queryAwardList(activityId);
        String key = "awardInfoList:" + activityId;
        stringRedisTemplate.opsForHash().putAll(key, idCountMap);
    }
}
